<template>
  <div class="coupon-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="优惠券名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" value="pending" />
            <el-option label="进行中" value="active" />
            <el-option label="已结束" value="ended" />
            <el-option label="已下架" value="disabled" />
          </el-select>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="searchForm.type" placeholder="请选择类型" clearable>
            <el-option label="满减券" value="discount" />
            <el-option label="代金券" value="cash" />
            <el-option label="折扣券" value="percentage" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>优惠券列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAdd">新增优惠券</el-button>
            <el-button type="success" @click="handleBatchIssue">批量发放</el-button>
          </div>
        </div>
      </template>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="优惠券名称" min-width="150" />
        <el-table-column prop="type" label="类型" width="100">
          <template #default="{ row }">
            <el-tag :type="getTypeTag(row.type)">
              {{ getTypeText(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="优惠金额/折扣" width="120">
          <template #default="{ row }">
            {{ formatValue(row) }}
          </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="使用门槛" width="120">
          <template #default="{ row }">
            {{ row.minAmount ? `满${row.minAmount}元可用` : '无门槛' }}
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开始时间" width="180" />
        <el-table-column prop="endTime" label="结束时间" width="180" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="发放数量" width="100" />
        <el-table-column prop="used" label="已使用" width="100" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">查看</el-button>
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="primary" link @click="handleIssue(row)">发放</el-button>
            <el-button
              v-if="row.status !== 'disabled'"
              type="danger"
              link
              @click="handleDelete(row)"
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 优惠券表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增优惠券' : '编辑优惠券'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="优惠券名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="优惠券类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option label="满减券" value="discount" />
            <el-option label="代金券" value="cash" />
            <el-option label="折扣券" value="percentage" />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠金额" prop="value" v-if="form.type !== 'percentage'">
          <el-input-number
            v-model="form.value"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="折扣比例" prop="value" v-else>
          <el-input-number
            v-model="form.value"
            :min="0"
            :max="100"
            :precision="0"
            :step="1"
            style="width: 200px"
          />
          <span class="form-tip">折</span>
        </el-form-item>
        <el-form-item label="使用门槛" prop="minAmount">
          <el-input-number
            v-model="form.minAmount"
            :min="0"
            :precision="2"
            :step="10"
            style="width: 200px"
          />
          <span class="form-tip">元（0表示无门槛）</span>
        </el-form-item>
        <el-form-item label="有效期" prop="timeRange">
          <el-date-picker
            v-model="form.timeRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="total">
          <el-input-number
            v-model="form.total"
            :min="1"
            :precision="0"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="使用说明" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入使用说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 发放优惠券对话框 -->
    <el-dialog
      v-model="issueDialogVisible"
      title="发放优惠券"
      width="500px"
    >
      <el-form
        ref="issueFormRef"
        :model="issueForm"
        :rules="issueRules"
        label-width="100px"
      >
        <el-form-item label="发放方式" prop="type">
          <el-radio-group v-model="issueForm.type">
            <el-radio label="user">指定用户</el-radio>
            <el-radio label="merchant">指定商家</el-radio>
            <el-radio label="all">所有用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户ID"
          prop="userIds"
          v-if="issueForm.type === 'user'"
        >
          <el-input
            v-model="issueForm.userIds"
            type="textarea"
            :rows="3"
            placeholder="请输入用户ID，多个ID用逗号分隔"
          />
        </el-form-item>
        <el-form-item
          label="商家ID"
          prop="merchantIds"
          v-if="issueForm.type === 'merchant'"
        >
          <el-input
            v-model="issueForm.merchantIds"
            type="textarea"
            :rows="3"
            placeholder="请输入商家ID，多个ID用逗号分隔"
          />
        </el-form-item>
        <el-form-item label="发放数量" prop="count">
          <el-input-number
            v-model="issueForm.count"
            :min="1"
            :precision="0"
            :step="1"
            style="width: 200px"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitIssue">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量发放对话框 -->
    <el-dialog
      v-model="batchIssueDialogVisible"
      title="批量发放优惠券"
      width="600px"
    >
      <el-form
        ref="batchIssueFormRef"
        :model="batchIssueForm"
        :rules="batchIssueRules"
        label-width="100px"
      >
        <el-form-item label="优惠券" prop="couponIds">
          <el-select
            v-model="batchIssueForm.couponIds"
            multiple
            placeholder="请选择优惠券"
            style="width: 100%"
          >
            <el-option
              v-for="item in availableCoupons"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发放对象" prop="targetType">
          <el-radio-group v-model="batchIssueForm.targetType">
            <el-radio label="user">指定用户</el-radio>
            <el-radio label="merchant">指定商家</el-radio>
            <el-radio label="all">所有用户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="用户ID"
          prop="userIds"
          v-if="batchIssueForm.targetType === 'user'"
        >
          <el-input
            v-model="batchIssueForm.userIds"
            type="textarea"
            :rows="3"
            placeholder="请输入用户ID，多个ID用逗号分隔"
          />
        </el-form-item>
        <el-form-item
          label="商家ID"
          prop="merchantIds"
          v-if="batchIssueForm.targetType === 'merchant'"
        >
          <el-input
            v-model="batchIssueForm.merchantIds"
            type="textarea"
            :rows="3"
            placeholder="请输入商家ID，多个ID用逗号分隔"
          />
        </el-form-item>
        <el-form-item label="每人发放" prop="count">
          <el-input-number
            v-model="batchIssueForm.count"
            :min="1"
            :precision="0"
            :step="1"
            style="width: 200px"
          />
          <span class="form-tip">张</span>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchIssueDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitBatchIssue">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getCouponList,
  createCoupon,
  updateCoupon,
  deleteCoupon,
  issueCoupon,
  batchIssueCoupon
} from '@/api/coupon'
import { checkPermission } from '@/permission'

const router = useRouter()

// 搜索表单
const searchForm = reactive({
  name: '',
  status: '',
  type: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  name: '',
  type: 'discount',
  value: 0,
  minAmount: 0,
  timeRange: [],
  total: 1000,
  description: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入优惠金额/折扣', trigger: 'blur' },
    { type: 'number', min: 0, message: '必须大于0', trigger: 'blur' }
  ],
  minAmount: [
    { required: true, message: '请输入使用门槛', trigger: 'blur' },
    { type: 'number', min: 0, message: '必须大于等于0', trigger: 'blur' }
  ],
  timeRange: [
    { required: true, message: '请选择有效期', trigger: 'change' },
    { type: 'array', min: 2, message: '请选择开始和结束时间', trigger: 'change' }
  ],
  total: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入使用说明', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 发放优惠券相关
const issueDialogVisible = ref(false)
const issueFormRef = ref(null)
const issueForm = reactive({
  type: 'user',
  userIds: '',
  merchantIds: '',
  count: 1
})

const issueRules = {
  type: [
    { required: true, message: '请选择发放方式', trigger: 'change' }
  ],
  userIds: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { pattern: /^[\d,]+$/, message: '请输入正确的用户ID，用逗号分隔', trigger: 'blur' }
  ],
  merchantIds: [
    { required: true, message: '请输入商家ID', trigger: 'blur' },
    { pattern: /^[\d,]+$/, message: '请输入正确的商家ID，用逗号分隔', trigger: 'blur' }
  ],
  count: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于0', trigger: 'blur' }
  ]
}

// 批量发放相关
const batchIssueDialogVisible = ref(false)
const batchIssueFormRef = ref(null)
const batchIssueForm = reactive({
  couponIds: [],
  targetType: 'user',
  userIds: '',
  merchantIds: '',
  count: 1
})

const batchIssueRules = {
  couponIds: [
    { required: true, message: '请选择优惠券', trigger: 'change' },
    { type: 'array', min: 1, message: '请至少选择一张优惠券', trigger: 'change' }
  ],
  targetType: [
    { required: true, message: '请选择发放对象', trigger: 'change' }
  ],
  userIds: [
    { required: true, message: '请输入用户ID', trigger: 'blur' },
    { pattern: /^[\d,]+$/, message: '请输入正确的用户ID，用逗号分隔', trigger: 'blur' }
  ],
  merchantIds: [
    { required: true, message: '请输入商家ID', trigger: 'blur' },
    { pattern: /^[\d,]+$/, message: '请输入正确的商家ID，用逗号分隔', trigger: 'blur' }
  ],
  count: [
    { required: true, message: '请输入每人发放数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '必须大于0', trigger: 'blur' }
  ]
}

// 可用的优惠券列表（用于批量发放）
const availableCoupons = computed(() => {
  return tableData.value.filter(item => item.status === 'active')
})

// 权限控制
const canManage = computed(() => checkPermission('coupon', 'manage'))
const canIssue = computed(() => checkPermission('coupon', 'issue'))

// 获取优惠券列表
const getList = async () => {
  loading.value = true
  try {
    const { data, total: totalCount } = await getCouponList({
      page: page.value,
      pageSize: pageSize.value,
      ...searchForm
    })
    tableData.value = data
    total.value = totalCount
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  getList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  handleSearch()
}

// 新增优惠券
const handleAdd = () => {
  dialogType.value = 'add'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    form[key] = key === 'type' ? 'discount' : key === 'total' ? 1000 : ''
  })
}

// 编辑优惠券
const handleEdit = (row) => {
  dialogType.value = 'edit'
  dialogVisible.value = true
  Object.keys(form).forEach(key => {
    if (key === 'timeRange') {
      form[key] = [row.startTime, row.endTime]
    } else {
      form[key] = row[key]
    }
  })
}

// 查看优惠券
const handleView = (row) => {
  router.push(`/coupon/detail/${row.id}`)
}

// 删除优惠券
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确认要下架该优惠券吗？下架后将无法继续发放和使用。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteCoupon(row.id)
    ElMessage.success('下架成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('下架优惠券失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    const [startTime, endTime] = form.timeRange
    const data = {
      ...form,
      startTime,
      endTime
    }
    delete data.timeRange
    
    const api = dialogType.value === 'add' ? createCoupon : updateCoupon
    const params = dialogType.value === 'add' ? data : { id: form.id, ...data }
    
    await api(params)
    ElMessage.success(dialogType.value === 'add' ? '新增成功' : '更新成功')
    dialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交表单失败:', error)
  }
}

// 发放优惠券
const handleIssue = (row) => {
  issueDialogVisible.value = true
  issueForm.type = 'user'
  issueForm.userIds = ''
  issueForm.merchantIds = ''
  issueForm.count = 1
  issueForm.couponId = row.id
}

// 提交发放
const submitIssue = async () => {
  if (!issueFormRef.value) return
  
  try {
    await issueFormRef.value.validate()
    const data = {
      type: issueForm.type,
      count: issueForm.count
    }
    
    if (issueForm.type === 'user') {
      data.userIds = issueForm.userIds.split(',').map(id => parseInt(id.trim()))
    } else if (issueForm.type === 'merchant') {
      data.merchantIds = issueForm.merchantIds.split(',').map(id => parseInt(id.trim()))
    }
    
    await issueCoupon(issueForm.couponId, data)
    ElMessage.success('发放成功')
    issueDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('发放优惠券失败:', error)
  }
}

// 批量发放
const handleBatchIssue = () => {
  batchIssueDialogVisible.value = true
  batchIssueForm.couponIds = []
  batchIssueForm.targetType = 'user'
  batchIssueForm.userIds = ''
  batchIssueForm.merchantIds = ''
  batchIssueForm.count = 1
}

// 提交批量发放
const submitBatchIssue = async () => {
  if (!batchIssueFormRef.value) return
  
  try {
    await batchIssueFormRef.value.validate()
    const data = {
      couponIds: batchIssueForm.couponIds,
      targetType: batchIssueForm.targetType,
      count: batchIssueForm.count
    }
    
    if (batchIssueForm.targetType === 'user') {
      data.userIds = batchIssueForm.userIds.split(',').map(id => parseInt(id.trim()))
    } else if (batchIssueForm.targetType === 'merchant') {
      data.merchantIds = batchIssueForm.merchantIds.split(',').map(id => parseInt(id.trim()))
    }
    
    await batchIssueCoupon(data)
    ElMessage.success('批量发放成功')
    batchIssueDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('批量发放失败:', error)
  }
}

// 分页相关
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  page.value = val
  getList()
}

// 获取类型标签样式
const getTypeTag = (type) => {
  const typeMap = {
    discount: 'success',
    cash: 'warning',
    percentage: 'info'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    discount: '满减券',
    cash: '代金券',
    percentage: '折扣券'
  }
  return typeMap[type] || '未知'
}

// 格式化优惠金额/折扣
const formatValue = (row) => {
  if (row.type === 'percentage') {
    return `${row.value}折`
  }
  return `¥${row.value.toFixed(2)}`
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    active: 'success',
    ended: 'warning',
    disabled: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '未开始',
    active: '进行中',
    ended: '已结束',
    disabled: '已下架'
  }
  return statusMap[status] || '未知'
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.coupon-list {
  padding: 20px;

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .form-tip {
    margin-left: 10px;
    color: var(--el-text-color-secondary);
    font-size: 14px;
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 